package org.hscoder.mongo.sync;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.apache.commons.lang.math.RandomUtils;
import org.bson.Document;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.function.Consumer;


public class DocumentOperation {

    public static void find(MongoClient client){

        MongoDatabase database = client.getDatabase("appdb");
        database.listCollectionNames().forEach((Consumer<String>) c -> {
            System.out.println(c);
        });

        MongoCollection<Document> collection = database.getCollection("test");

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date time = new Date();
        System.out.println(df.format(time));

        long id = RandomUtils.nextLong();
        Document document = new Document();
        document.put("_id", id);
        document.put("time", time);

        collection.insertOne(document);

        System.out.println("===========");
        Iterable<Document> it = collection.find(new Document("_id", id));
        it.forEach( doc -> {
            System.out.println(doc.toJson());
            Date t = doc.getDate("time");
            System.out.println(df.format(t));
        });
    }
}
